package fhp.hlhj.giantfold.converter;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

/**
 * author: ShuaiTao
 * data: on 2017\11\9 0009 11:03
 * E-Mail: bill_dream@sina.com
 */
public abstract class CustomConverter<T> extends AbsCallback<T>{
    private Type type;
    private Class<T> clazz;
    public CustomConverter(Type type) {
        this.type = type;
    }
    public CustomConverter(Class<T> clazz) {
        this.clazz = clazz;
    }
    public CustomConverter(){
    }
    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body==null)
        return null;
        T data = null;
        Gson g = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        if (type!=null){
            data=g.fromJson(jsonReader,type);
        }else if (clazz!=null){
            data=g.fromJson(jsonReader,clazz);
        }else {
            Type genType = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            data=g.fromJson(jsonReader,type);
        }
        return data;
    }
}
